const cloud = require("@cloudbase/node-sdk");

const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV,
});

var db = app.database();
const _ = db.command
const $ = db.command.aggregate
const ZXBbsData = db.collection('ZX-Bbs-Data')
const ZXBbsReply = db.collection('ZX-Bbs-Reply')
const ZXBbsReplyMessage = db.collection('ZX-Bbs-Reply-Message')
// const nowDate = new Date().getTime()
const nowDate = db.serverDate()

// 获取openId云函数入口函数
exports.main = async (event,context,token,gameId) => {
    process.env.TZ = 'Asia/Shanghai'
    const api = event.api
    var params = {}

    // 帖子默认需要的一些内容
    var status = 1 //1有效帖子,-1无效帖子
    var create_time = nowDate //创建时间
    var update_time = nowDate //更新时间
    // 用到的一些描述
    const bbsType = [
        { label: "八卦闲聊", value: 1},
        { label: "东方需求", value: 2},
        { label: "东方攻略", value: 3},
        { label: "心得交流", value: 4},
        { label: "东方活动", value: 5},
    ]

    if(token){
        if(api=='api-bbs-add'){
            event.data.status = status
            event.data.create_time = create_time
            event.data.update_time = update_time
            event.data.reply_last_time = 0 //最后回复时间
            event.data.userId = token
            event.data.zanNumber = 0
            event.data.topNumber = 0
            event.data.hotNumber = 0
            event.data.isStop = false
            return await ZXBbsData.add(event.data)
        }
    }
    // 帖子详情
    if(api=="api-bbs-detail"){
        let _id = event.data._id
        let userId = event.data.userId
        let params2 = {}
        params2.cBbsId = _id
        if(userId){
            params2.userId = userId
        }
        if(_id){
            // return (await ZXBbsData.doc(_id).get()).data[0]
            const res = await db
            .collection('ZX-Bbs-Data')
            .aggregate()
            .lookup({
                from: 'ZX-Bbs-Reply',
                let: {
                    cId: '$_id',
                },
                pipeline: $.pipeline()
                    .match(
                        _.expr(
                            $.and([
                                $.eq(['$cBbsId', '$$cId']),
                            ])
                        )
                    )
                    .lookup({
                        from: 'ZX-User',
                        localField: 'userId',
                        foreignField: '_id',
                        as: 'userList2'
                    })
                    .replaceRoot({
                        newRoot: $.mergeObjects([$.arrayElemAt(['$userList2', 0]), '$$ROOT'])
                    })
                    .lookup({
                        from: 'ZX-Bbs-Reply-Message',
                        let: {
                            cId: '$_id',
                        },
                        pipeline: $.pipeline()
                            .match(
                                _.expr(
                                    $.and([
                                        $.eq(['$replyId', '$$cId']),
                                    ])
                                )
                            )
                            .lookup({
                                from: 'ZX-User',
                                localField: 'toUserId',
                                foreignField: '_id',
                                as: 'replyUserListTo'
                            })
                            .replaceRoot({
                                newRoot: $.mergeObjects([$.arrayElemAt(['$replyUserListTo', 0]), '$$ROOT'])
                            })
                            .addFields({
                                toGameName: '$gameName',
                            })
                            .project({
                                replyUserListTo: 0,
                                gameCode: 0,
                                gameId: 0,
                                password: 0,
                                powerInfo: 0,
                                status: 0,
                                gameName: 0,
                            })
                            .lookup({
                                from: 'ZX-User',
                                localField: 'userId',
                                foreignField: '_id',
                                as: 'replyUserList'
                            })
                            .replaceRoot({
                                newRoot: $.mergeObjects([$.arrayElemAt(['$replyUserList', 0]), '$$ROOT'])
                            })
                            .project({
                                replyUserList: 0,
                                gameCode: 0,
                                gameId: 0,
                                password: 0,
                                powerInfo: 0,
                                status: 0,
                            })
                            .addFields({
                                gameName: '$gameName',
                            })
                            
                        .done(),
                        as: 'messageList'
                    })
                    .sort({
                        create_time: 1,
                    })
                    .project({
                        userList2: 0,
                        gameCode: 0,
                        gameId: 0,
                        password: 0,
                        powerInfo: 0,
                        status: 0,
                    })
                    .skip((event.data.pageIndex - 1) * event.data.pageSize)
                    .limit(event.data.pageSize)
                .done(),
                as:'replyList',
            })
            // .replaceRoot({
            //     newRoot: $.mergeObjects(
            //         [$.arrayElemAt(['$replyList', 0]), '$$ROOT'],
            //     ),
            // })
            .lookup({
                from: 'ZX-User',
                localField: 'userId',
                foreignField: '_id',
                as: 'userList'
            })
            .replaceRoot({
                newRoot: $.mergeObjects(
                    [$.arrayElemAt(['$userList', 0]), '$$ROOT']
                ),
            })
            .project({
                userList: 0,
                password: 0,
                powerInfo: 0,
            })
            .match({
                _id: _id
            })
            // .sort({
            //     "class": 1,
            // })
            .end()

            const total = await db
            .collection('ZX-Bbs-Reply')
            .aggregate()
            .match({
                cBbsId: _id
            })
            .lookup({
                from: 'ZX-Bbs-Data',
                localField: 'cBbsId',
                foreignField: '_id',
                as: 'userList'
            })
            .count('count')
            .end()

            let count = total.data.length>0?total.data[0].count:0

            return {
                data: res.data[0],
                total: count,
            }

        }
    }
    // 论坛帖子列表
    if(api=="api-bbs-list"){
        const res = await db
        .collection('ZX-Bbs-Data')
        .aggregate()
        .lookup({
            from: 'ZX-Bbs-Reply',
            let: {
                cId: '$_id',
            },
            pipeline: $.pipeline()
                .match(
                    _.expr(
                        $.and([
                          $.eq(['$cBbsId', '$$cId']),
                        ])
                      )
                )
                .lookup({
                    from: 'ZX-User',
                    localField: 'userId',
                    foreignField: '_id',
                    as: 'userList2'
                })
                .replaceRoot({
                    newRoot: $.mergeObjects([$.arrayElemAt(['$userList2', 0]), '$$ROOT'])
                })
                .addFields({
                    lastGameName: '$gameName',
                    lastReplyTime: '$create_time',
                })
                .sort({
                    create_time: -1, //按时间从大到小排序，方便提取最后回复的人信息
                })
                .project({
                    userList2: 0,
                    password: 0,
                    powerInfo: 0,
                    status: 0,
                    cBbsId: 0,
                    content: 0,
                    gameCode: 0,
                    gameId: 0,
                    gameName: 0,
                    create_time: 0,
                    qq: 0,
                    userId: 0,
                    _id: 0,
                })
            .done(),
            as:'replyList',
        })
        .replaceRoot({
            newRoot: $.mergeObjects(
                [$.arrayElemAt(['$replyList', 0]), '$$ROOT'],
            ),
        })
        .lookup({
            from: 'ZX-User',
            localField: 'userId',
            foreignField: '_id',
            as: 'userList'
        })
        .replaceRoot({
            newRoot: $.mergeObjects(
                [$.arrayElemAt(['$userList', 0]), '$$ROOT']
            ),
        })
        .addFields({
            replyCount: $.size('$replyList') ,//统计回复数
            createName: '$gameName',
            createTime: '$create_time',
            cTypeList: bbsType,
        })
        .addFields({
            typeStr: $.arrayElemAt(['$cTypeList.label', $.indexOfArray(['$cTypeList.value', '$type'])]),
        })
        .project({
            // userList: 0,
            replyList: 0,
            password: 0,
            powerInfo: 0,
            create_time: 0,
            cTypeList: 0,
        })
        .match({
            status: 1,
        })
        .sort({
            topNumber: -1,
            lastReplyTime: -1,
            createTime: -1,
        })
        .skip((event.data.pageIndex - 1) * event.data.pageSize)
        .limit(event.data.pageSize)
        .end()

        const list = res.data
        const total = (await ZXBbsData.where({
            status: 1,
        }).count()).total

        return {
            list: list,
            total: total,
        }
    }

    // 提交帖子回复
    if(api=='api-bbs-reply-add'){
        return await ZXBbsReply.add({
            cBbsId: event.data._id,
            userId: token,
            create_time: create_time,
            content: event.data.content,
        })
    }

    // 提交回复用户
    if(api=='api-bbs-reply-user-add'){
        let replyId = event.data.replyId
        let cBbsId = event.data.cBbsId
        if(replyId){
            return await ZXBbsReplyMessage.add({
                replyId: replyId,
                userId: token,
                cBbsId: cBbsId,
                toUserId: event.data.toUserId,
                content: event.data.content,
            })
        }
    }


    // 取消置顶
    if(api=='api-bbs-update-clear-top'){
        const _id = event.data._id
        return await ZXBbsData.doc(_id).update({
            topNumber: 0,
        })
    }

    // 置顶、电子更新
    if(api=='api-bbs-update'){

        const type = event.data.type
        const _id = event.data._id
        const status = event.data.status

        if(type=='top'){
            const res =  await ZXBbsData.doc(_id).update({
                topNumber: _.inc(1),
            })
            return res
        }else if(type=='zan'){
            let params = {}
            params.zanUserList = _.addToSet(token)
            params.zanNumber =  _.inc(1)
            const res =  await ZXBbsData.doc(_id).update(params)
            return res
        }else if(type=='del'){
            const res =  await ZXBbsData.doc(_id).update({
                status: status,
            })
            return res
        }else if(type=='content'){
            const res =  await ZXBbsData.doc(_id).update({
                content: event.data.content,
            })
            return res
        }else if(type=='replyContent'){
            const res =  await ZXBbsReply.doc(_id).update({
                content: event.data.content,
            })
            return res
        }else if(type=='replyDel'){
            const res =  await ZXBbsReply.doc(_id).remove()
            return res
        }

        
    }


    

    if(api=='api-bbs-enum'){
        if(event.data.type=='bbsType'){
            return bbsType
        }
    }



    if(api=="api-bbs-detail2"){
        let _id = event.data._id
        let userId = event.data.userId
        let params2 = {}
        params2.cBbsId = _id
        if(userId){
            params2.userId = userId
        }
        if(_id){
            // return (await ZXBbsData.doc(_id).get()).data[0]
            const res = await db
            .collection('ZX-Bbs-Data')
            .aggregate()
            .lookup({
                from: 'ZX-Bbs-Reply',
                let: {
                    cId: '$_id',
                },
                pipeline: $.pipeline()
                    .match(
                        // _.expr(
                        //     $.and([
                        //         $.eq(['$cBbsId', '$$cId']),
                        //     ])
                        // )
                        params2
                    )
                    .lookup({
                        from: 'ZX-User',
                        localField: 'userId',
                        foreignField: '_id',
                        as: 'userList2'
                    })
                    .replaceRoot({
                        newRoot: $.mergeObjects([$.arrayElemAt(['$userList2', 0]), '$$ROOT'])
                    })
                    .lookup({
                        from: 'ZX-Bbs-Reply-Message',
                        let: {
                            cId: '$_id',
                        },
                        pipeline: $.pipeline()
                            .match(
                                _.expr(
                                    $.and([
                                        $.eq(['$replyId', '$$cId']),
                                    ])
                                )
                            )
                            .lookup({
                                from: 'ZX-User',
                                localField: 'toUserId',
                                foreignField: '_id',
                                as: 'replyUserListTo'
                            })
                            .replaceRoot({
                                newRoot: $.mergeObjects([$.arrayElemAt(['$replyUserListTo', 0]), '$$ROOT'])
                            })
                            .addFields({
                                toGameName: '$gameName',
                            })
                            .project({
                                replyUserListTo: 0,
                                gameCode: 0,
                                gameId: 0,
                                password: 0,
                                powerInfo: 0,
                                status: 0,
                                gameName: 0,
                            })
                            .lookup({
                                from: 'ZX-User',
                                localField: 'userId',
                                foreignField: '_id',
                                as: 'replyUserList'
                            })
                            .replaceRoot({
                                newRoot: $.mergeObjects([$.arrayElemAt(['$replyUserList', 0]), '$$ROOT'])
                            })
                            .project({
                                replyUserList: 0,
                                gameCode: 0,
                                gameId: 0,
                                password: 0,
                                powerInfo: 0,
                                status: 0,
                            })
                            .addFields({
                                gameName: '$gameName',
                            })
                            
                        .done(),
                        as: 'messageList'
                    })
                    .sort({
                        create_time: 1,
                    })
                    .project({
                        userList2: 0,
                        gameCode: 0,
                        gameId: 0,
                        password: 0,
                        powerInfo: 0,
                        status: 0,
                    })
                    .skip((event.data.pageIndex - 1) * event.data.pageSize)
                    .limit(event.data.pageSize)
                .done(),
                as:'replyList',
            })
            // .replaceRoot({
            //     newRoot: $.mergeObjects(
            //         [$.arrayElemAt(['$replyList', 0]), '$$ROOT'],
            //     ),
            // })
            .lookup({
                from: 'ZX-User',
                localField: 'userId',
                foreignField: '_id',
                as: 'userList'
            })
            .replaceRoot({
                newRoot: $.mergeObjects(
                    [$.arrayElemAt(['$userList', 0]), '$$ROOT']
                ),
            })
            .project({
                userList: 0,
                password: 0,
                powerInfo: 0,
            })
            .match({
                _id: _id
            })
            // .sort({
            //     "class": 1,
            // })
            .end()

            const total = await db
            .collection('ZX-Bbs-Reply')
            .aggregate()
            .match(params2)
            .lookup({
                from: 'ZX-Bbs-Data',
                localField: 'cBbsId',
                foreignField: '_id',
                as: 'userList'
            })
            .count('count')
            .end()

            let count = total.data.length>0?total.data[0].count:0

            return {
                data: res.data[0],
                total: count,
            }

        }
    }

};